//
//  HomeViewController.m
//  TravelDiary
//
//  Created by lanou3g on 15/11/11.
//  Copyright © 2015年 YDB MAC. All rights reserved.
//

#import "HomeViewController.h"
#import <AFNetworking/AFNetworking.h>
#import "LYYTitleButton.h"
#import "LYYSearchBar.h"
#import "SceneryCell.h"
#import "ZCControl.h"
#import "WheelPic.h"
#import "Scenery.h"
#import "SDCycleScrollView.h"
#import "CircleView.h"
#import <UIImageView+WebCache.h>
#import "WheelWebView.h"
#import "DestinationViewController.h"

#import "LocationViewController.h"
#import "SceneryDetailViewController.h"
#import "CityButtonViewController.h"

#import "FanProgress3D/FanProgress3D.h"
#import "AnimationToll/AnimationTool.h"
#import "UserLocationManager.h"
#import "LYYSearchViewController.h"
#import "FootmarkViewController.h"

#import "CityListViewController.h"
#import "SelectChatRoomTableViewController.h"
#import <AVOSCloud.h>


#define LYYTitleButtonDownTag 0
#define LYYTitleButtonUpTag -1


#define wheelPicURL @"http://open.qyer.com/qyer/recommands/entry?app_installtime=1435837675&client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&page=1&track_app_channel=App%2520Store&track_app_version=6.3&track_device_info=iPhone7%2C2&track_deviceid=94600906-5BB7-43E7-9E16-C479A03EE469&track_os=ios%25208.3&v=1"

#define kFJUrl @"http://api.photochina.china.cn/phone/category_4_%d_10.html"//风景风光
#define kFJDetailUrl @"http://api.photochina.china.cn/phone/articles_4_%@.html"

#define kGJUrl @"http://api.photochina.china.cn/phone/category_6_%d_10.html"//古风古景
#define kGJDetailUrl @"http://api.photochina.china.cn/phone/articles_6_%@.html"

@interface HomeViewController ()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate,SDCycleScrollViewDelegate,cityListVCDelegate>
{
    
    UIView *_sectionView;   //段头的View
    UIScrollView *_adScrollView;
    UIPageControl *_pageControl;
    AFHTTPSessionManager *_manager;

    SDCycleScrollView *cycleScrollView;
 
    int currentPage1;
    int currentPage2;
    
    NSString *cityname;
    LYYTitleButton *Titlebutton;
    
}
/**
 *轮播图数据数组
 */
@property (nonatomic, strong) NSMutableArray *wheelPicArray;
@property (nonatomic, strong) NSMutableArray *wheelPicUrl;
@property (nonatomic, strong) NSMutableArray *wheelPicTitle;
/**
 *cell数据数组
 */
@property (nonatomic, strong) NSMutableArray *sceneryArray;

/**
 *第一个区头内容
 */
@property (nonatomic, strong) UIView *headView0;
@property (nonatomic, strong) UIView *lineLeft;
@property (nonatomic, strong) UIView *lineRight;

@property (nonatomic, strong) UISegmentedControl *seg;
@property (nonatomic, strong) NSString *str;

@property (nonatomic, strong) UITableView *tableView;


@end
static int flag = 0 ;
@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:6/255.0 green:160/255.0 blue:250/255.0 alpha:1.0];
    
 
    //1.设置导航栏的内容
    [self loadNavBar];
    
    //2.请求轮播图数据
    [self loadWheelPicData];
    //3.请求风景数据
    [self loadScenData];
    
    //4.创建tableView
    [self createTableView];
    
    currentPage1 = 0;
    currentPage2 = 0;
    
  
    
}

#pragma mark - 轮播图数据请求
- (void)loadWheelPicData{
    
    //1.创建请求管理对象
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    self.wheelPicArray = [NSMutableArray array];
    self.wheelPicUrl = [NSMutableArray array];
    self.wheelPicTitle = [NSMutableArray array];
    
    //2.发送请求
    [mgr GET:wheelPicURL parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        NSDictionary *data = responseObject[@"data"];
        NSMutableArray *subject = data[@"subject"];
        for (NSDictionary *dict in subject) {
            [self.wheelPicUrl addObject:dict[@"photo"]];
            [self.wheelPicTitle addObject:dict[@"title"]];
            
            WheelPic *model = [[WheelPic alloc]init];
            
            [model setValuesForKeysWithDictionary:dict];
            [self.wheelPicArray addObject:model];
        }
        [_tableView reloadData];
        
        
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        
    }];
        
    
}
#pragma mark - 请求风景数据
- (void)loadScenData{
    //1.创建请求管理对象
    _manager=[AFHTTPSessionManager manager];
    _manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    self.sceneryArray = [NSMutableArray array];
    if (_seg.selectedSegmentIndex == 0) {
        _str = [NSString stringWithFormat:kFJUrl,++currentPage1];
    }else{
        _str = [NSString stringWithFormat:kGJUrl,++currentPage2];
    }
    [_manager GET:_str parameters:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        if ([responseObject isKindOfClass:[NSData class]]) {
            NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSArray *array = dict[@"items"];
            for (NSDictionary *dic in array) {
                
                Scenery *sceneryModel = [[Scenery alloc]init];
                [sceneryModel setValuesForKeysWithDictionary:dic];
                NSDictionary *dictImg =dic[@"img"];
                sceneryModel.picUrl = dictImg[@"picUrl"];
                [self.sceneryArray addObject:sceneryModel];
              
                
            }
            [_tableView reloadData];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    
}


#pragma mark-navbar添加
- (void)loadNavBar{
    
    //左边按钮
    LYYTitleButton *titleButton = [LYYTitleButton titleButton];
    //图标
    [titleButton setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];
    //位置和尺寸
    titleButton.frame = CGRectMake(0, 0, 0, 40);
    titleButton.titleLabel.font = [UIFont systemFontOfSize:15];
    
    [titleButton setTitle:@"全国" forState:UIControlStateNormal];
    
    [titleButton addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:titleButton];
    
    
    //中间按钮
    LYYSearchBar *searchBar = [LYYSearchBar searchBar];
    searchBar.delegate = self;
    //当点击UITextField的时候不要弹出键盘
    searchBar.inputView = [[UIView alloc]initWithFrame:CGRectZero];
    //尺寸
    searchBar.frame = CGRectMake(0, 0, self.view.frame.size.width - 100, 30);
    //设置中间的标题内容
    self.navigationItem.titleView = searchBar;
    
    
    Titlebutton = titleButton;
    //添加通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(citychange:) name:@"location" object:cityname];
}

-(void)citychange:(NSNotification *)center
{
    [Titlebutton setTitle:center.object forState:UIControlStateNormal];
}

#pragma mark - 地点位置的选择
- (void)titleClick:(LYYTitleButton *)titleButton{
    CityListViewController *cityListVC = [[CityListViewController alloc]init];
    cityListVC.delegate = self;
    [self.navigationController showViewController:cityListVC sender:self];
}
- (void)passValueToHospital:(NSString *)str{
    
    [Titlebutton setTitle:str forState:UIControlStateNormal];
    
}

#pragma mark 创建TableView
- (void)createTableView
{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0,0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.view addSubview:_tableView];
    
    
}
#pragma mark tableView代理

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.sceneryArray.count;
    
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 170;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"SceneryCell";
    SceneryCell *cell= [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (!cell) {
        [tableView registerNib:[UINib nibWithNibName:@"SceneryCell" bundle:nil] forCellReuseIdentifier:CellIdentifier];
        cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    }
    Scenery *model = self.sceneryArray[indexPath.row];
    
    cell.selectedBackgroundView = [[UIView alloc]init];
    
    [cell bindModel:model];
    
    return cell;
}
#pragma mark - cell的点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    SceneryDetailViewController *sceneryVC = [[SceneryDetailViewController alloc]init];

   Scenery *sceneryModel = self.sceneryArray[indexPath.row];

    
    if (_seg.selectedSegmentIndex == 0) {
        if (self.sceneryArray.count == 0) {
            return;
        }
        sceneryVC.detailUrl = [NSString stringWithFormat:kFJDetailUrl,sceneryModel.id];
        sceneryVC.titleName = sceneryVC.title;
    }else{
        sceneryVC.detailUrl = [NSString stringWithFormat:kGJDetailUrl,sceneryModel.id];
        sceneryVC.titleName = sceneryVC.title;
    }
    [self.navigationController pushViewController:sceneryVC animated:YES];
}
#pragma mark - 头部view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    _headView0 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 100, 100)];
    _headView0.backgroundColor = [UIColor colorWithRed:245/255.0 green:245/255.0 blue:245/255.0 alpha:1.0];
    //轮播图
    [self addWheelPic];
    

    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(cycleScrollView.frame), self.view.frame.size.width, 120)];
    imageView.image = [UIImage imageNamed:@"back0"];
    [_headView0 addSubview:imageView];
    imageView.userInteractionEnabled = YES;
    //四个圆形按钮
    [self addCircleView:imageView];
    
    
    UIView *cityView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(imageView.frame), self.view.frame.size.width, 150)];
    cityView.backgroundColor = [UIColor whiteColor];
    [_headView0 addSubview:cityView];
    UIView *city = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 50)];
    city.backgroundColor = [UIColor whiteColor];
    [cityView addSubview:city];
    //热门城市
    [self addCityInfo:cityView];
    
    UIView *sceneryView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(cityView.frame)-5, self.view.frame.size.width, 50)];
    sceneryView.backgroundColor = [UIColor whiteColor];
    
    [_headView0 addSubview:sceneryView];
    
    UIImageView *image1 = [[UIImageView alloc]initWithFrame:CGRectMake(20, 5, 30, 30)];
    image1.image = [UIImage imageNamed:@"scen"];
    [sceneryView addSubview:image1];
    UIImageView *image2 = [[UIImageView alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2+20, 5, 30, 30)];
    image2.image = [UIImage imageNamed:@"scen"];
    [sceneryView addSubview:image2];
    //风景
    [self addScenery:sceneryView];
    
    self.lineLeft = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(sceneryView.frame), self.view.frame.size.width/2, 2)];
    self.lineLeft.backgroundColor = [UIColor colorWithRed:3/255.0 green:189/255.0 blue:249/255.0 alpha:1.0];
    [_headView0 addSubview:self.lineLeft];
    
    
    self.lineRight = [[UIView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(_lineLeft.frame), CGRectGetMaxY(sceneryView.frame), self.view.frame.size.width/2, 2)];
    self.lineRight.backgroundColor = [UIColor colorWithRed:3/255.0 green:189/255.0 blue:249/255.0 alpha:1.0];
    [_headView0 addSubview:self.lineRight];
    if (flag == 0) {
        self.lineLeft.hidden = NO;
        self.lineRight.hidden = YES;
    }else{
        self.lineLeft.hidden = YES;
        self.lineRight.hidden = NO;
    }
    
    return _headView0;
    
    
}
#pragma mark - head的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    return self.view.frame.size.height/3+120+200;
    
}
#pragma mark - 景色
- (void)addScenery:(UIView *)cityView{
    _seg = [[UISegmentedControl alloc]initWithItems:@[@"风景风光",@"古风古景"]];
    _seg.frame = CGRectMake(0, 0, self.view.frame.size.width, 49);
    _seg.selectedSegmentIndex = flag;
    if (flag == 0) {
        self.lineLeft.hidden = NO;
        self.lineRight.hidden = YES;
    }else{
        self.lineLeft.hidden = YES;
        self.lineRight.hidden = NO;
    }
    
    //清除segmentedControl的边框颜色
    _seg.tintColor = [UIColor clearColor];
    NSDictionary* selectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],NSForegroundColorAttributeName: [UIColor colorWithRed:3/255.0 green:189/255.0 blue:249/255.0 alpha:1.0]};
    [_seg setTitleTextAttributes:selectedTextAttributes forState:UIControlStateSelected];//设置文字属性
    NSDictionary* unselectedTextAttributes = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:16],NSForegroundColorAttributeName: [UIColor grayColor]};
    [_seg setTitleTextAttributes:unselectedTextAttributes forState:UIControlStateNormal];
    [cityView addSubview:_seg];
   
    
    
    [_seg addTarget:self action:@selector(segClick:) forControlEvents:UIControlEventValueChanged];
    
    
    
}
- (void)segClick:(UISegmentedControl *)seg{
    //switch给定一个条件快速跳到条件位置
    switch (seg.selectedSegmentIndex) {
        case 0:
        {
            
            self.lineRight.hidden = YES;
            self.lineLeft.hidden = NO;
            flag = 0;
            [self loadScenData];
        }
            break;
        case 1:
        {
            self.lineRight.hidden = NO;
            self.lineLeft.hidden = YES;
            flag = 1;
            [self loadScenData];
            
        }
            break;
                default:
            break;
    }
}
#pragma mark - //热门城市
- (void)addCityInfo:(UIView *)cityView{
    UIImageView *iconCity = [[UIImageView alloc]initWithFrame:CGRectMake(30, 10, 30, 30)];
    iconCity.image = [UIImage imageNamed:@"iconfont-chengshishitu"];
    [cityView addSubview:iconCity];
    UILabel *cityLabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(iconCity.frame)+10, 10, self.view.frame.size.width - 95, 30)];
    cityLabel.text = @"热门城市（全景图）";
    [cityView addSubview:cityLabel];
    
    CGFloat w = self.view.frame.size.width /4;
    NSArray *array = [NSArray arrayWithObjects:@"北京",@"福建",@"海南",@"河南",@"贵州",@"广东",@"上海",@"山东", nil];
    
    for (int i = 0; i<8; i++) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(i%4*w-1, i/4*40+50, w+1, 41);
        button.layer.borderWidth = 1;
        button.layer.borderColor = [UIColor lightGrayColor].CGColor;
        [button setTitle:array[i] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithRed:100/255.0 green:100/255.0 blue:100/255.0 alpha:1.0] forState:UIControlStateNormal];
        [button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [cityView addSubview:button];
    }
}
#pragma mark- 热门城市点击事件
- (void)buttonClick:(UIButton *)sender{
    
    CityButtonViewController *cityVC = [[CityButtonViewController alloc]init];
    //跳转动画效果
    [self.navigationController.view.layer addAnimation:[AnimationTool addAnimationWithAnimationSubType:kCATransitionFromRight withType:@"rippleEffect" duration:1.0f] forKey:nil];
    cityVC.cityName = sender.titleLabel.text;
    
    [self.navigationController pushViewController:cityVC animated:YES];
}
#pragma mark－轮播图添加
- (void)addWheelPic{
    cycleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height/3) imageURLStringsGroup:nil]; 
    cycleScrollView.pageControlAliment = SDCycleScrollViewPageContolAlimentRight;
    cycleScrollView.delegate = self;
    cycleScrollView.titlesGroup = self.wheelPicTitle;
    cycleScrollView.dotColor = [UIColor colorWithRed:3/255.0 green:189/255.0 blue:249/255.0 alpha:1.0];// 自定义分页控件小圆标颜色
    cycleScrollView.placeholderImage = [UIImage imageNamed:@"placeholder"];
    [_headView0 addSubview:cycleScrollView];
    cycleScrollView.imageURLStringsGroup = self.wheelPicUrl;
}

#pragma mark - SDCycleScrollViewDelegate   轮播图点击事件

- (void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
    WheelWebView *webVC = [[WheelWebView alloc]init];
    WheelPic *model = self.wheelPicArray[index];
    webVC.url = model.url;
    [self.navigationController pushViewController:webVC animated:YES];
}
#pragma mark- 圆圈按钮的添加
- (void)addCircleView:(UIImageView *)imageView{
    
    CGFloat w = 60;
    CGFloat h = 100;
    CGFloat ww = (self.view.frame.size.width - w*4)/5;
    //目的地
    CircleView *destination = [[CircleView alloc]initWithFrame:CGRectMake(ww, 15, w, h)];
    [self setupView:destination ImageBackgroundColor:[UIColor colorWithRed:51/255.0 green:255/255.0 blue:171/255.0 alpha:1.0] labelText:@"目的地" imageNamed:@"iconfont-mudedidangqian" imageView:imageView];
    [destination addTarget:self action:@selector(descriptionClick:) forControlEvents:UIControlEventTouchUpInside];
    
    //攻略
    CircleView *strategy = [[CircleView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(destination.frame)+ww, 15, w, h)];
    [self setupView:strategy ImageBackgroundColor:[UIColor orangeColor] labelText:@"发现" imageNamed:@"iconfont-gonglve" imageView:imageView];
    [strategy addTarget:self action:@selector(strategyClick:) forControlEvents:UIControlEventTouchUpInside];
    
    //聊天室
    CircleView *chat = [[CircleView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(strategy.frame)+ww, 15, w, h)];
    [self setupView:chat ImageBackgroundColor:[UIColor colorWithRed:58/255.0 green:182/255.0 blue:255/255.0 alpha:1.0] labelText:@"聊天室" imageNamed:@"iconfont-comments" imageView:imageView];
    [chat addTarget:self action:@selector(chatClick:) forControlEvents:UIControlEventTouchUpInside];
    
    //位置
    CircleView *location = [[CircleView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(chat.frame)+ww, 15, w, h)];
    [self setupView:location ImageBackgroundColor:[UIColor colorWithRed:244/255.0 green:118/255.0 blue:255/255.0 alpha:1.0] labelText:@"位置" imageNamed:@"iconfont-weizhi" imageView:imageView];
    [location addTarget:self action:@selector(locationClick:) forControlEvents:UIControlEventTouchUpInside];
    
}
#pragma mark - 目的地点击事件
- (void)descriptionClick:(CircleView *)sender{
    
    DestinationViewController *desVC = [[DestinationViewController alloc]init];
    [self.navigationController pushViewController:desVC animated:YES];
}

#pragma mark - 攻略点击事件
- (void)strategyClick:(CircleView *)sender{
    FootmarkViewController *footVC = [[FootmarkViewController alloc]init];
    [self.navigationController pushViewController:footVC animated:YES];
    
}

#pragma mark - 聊天室点击事件
- (void)chatClick:(CircleView *)sender{
    AVUser * currentUser = [AVUser currentUser];
    
    if (currentUser != nil ) {
        SelectChatRoomTableViewController * lec =[[SelectChatRoomTableViewController alloc] init];
        
        [self.navigationController pushViewController:lec animated:YES];
        NSLog(@"123123");
        
    }else{
        
                    UIAlertView*aler = [[UIAlertView alloc] initWithTitle:@"提示" message:@"您未登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                    [aler show];
        
    }
    
   
    
}

#pragma mark - 位置点击事件
- (void)locationClick:(CircleView *)sender{
    LocationViewController *locationVC = [[LocationViewController alloc]init];
    [self.navigationController.view.layer addAnimation:[AnimationTool addAnimationWithAnimationSubType:kCATransitionFromRight withType:@"rippleEffect" duration:1.0f] forKey:nil];
    locationVC.titleStr = @"位置";
    
    [self.navigationController pushViewController:locationVC animated:YES];
    
}
/**
 *初始化一个CircleView
 */
- (void)setupView:(CircleView *)view ImageBackgroundColor:(UIColor *)imageBackgroundColor labelText:(NSString *)labelText imageNamed:(NSString *)imageNamed imageView:(UIImageView *)imageView{
    
    view.cimageView.backgroundColor = imageBackgroundColor;
    view.textLabel.textColor = [UIColor blackColor];
    view.textLabel.text = labelText;
    view.cimageView.image = [UIImage imageNamed:imageNamed];
    [imageView addSubview:view];
    
}

#pragma mark ---当光标定位到searchbar上时执行事件
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    
    LYYSearchViewController *searchVC = [[LYYSearchViewController alloc]init];
    [searchVC.searchBar isFirstResponder];
    [self.navigationController pushViewController:searchVC animated:YES];
    return YES;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
